package org.dromara.finance.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.finance.domain.PurchaseContract;
import org.dromara.finance.domain.bo.SaleContractBo;
import org.dromara.finance.domain.report.*;
import org.dromara.finance.domain.vo.PurchaseContractVo;
import org.dromara.finance.domain.vo.SaleContractVo;
import org.dromara.finance.mapper.*;
import org.dromara.finance.service.IReportService;
import org.dromara.finance.utils.ReportConverter;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@RequiredArgsConstructor
@Service
public class ReportServiceImpl implements IReportService {

    private final SaleContractMapper saleContractMapper;
    private final SaleInvoiceMapper saleInvoiceMapper;
    private final BillMapper billMapper;
    private final PurchaseContractMapper purchaseContractMapper;
    private final PurchaseInvoiceMapper purchaseInvoiceMapper;

    @Override
    public List<SaleContractReportVO> getContractReport(SaleContractBo bo) {
        List<SaleContractVo> contractVos = saleContractMapper.selectReportList(bo);
        List<SaleContractReportVO> result = new ArrayList<>();
        for (SaleContractVo contract : contractVos) {
            SaleContractReportVO vo = ReportConverter.toSaleReportVO(contract);

            // 2. 查询销售发票明细
            List<SaleInvoiceDetailVO> invoices = saleInvoiceMapper.selectByContractId(contract.getId());
            vo.setSaleInvoiceDetails(invoices);

            // 3. 查询收款明细
            List<ReceiveBillVO> receiveBills = billMapper.selectReceivesByContractId(contract.getId());
            vo.setReceiveBills(receiveBills);

            // 4. 查询采购合同及其子表
            List<PurchaseContractVo> purchaseContracts = purchaseContractMapper.selectBySaleContractId(contract.getId());
            List<PurchaseContractReportVO> purchaseVOs = new ArrayList<>();
            for (PurchaseContractVo pc : purchaseContracts) {
                PurchaseContractReportVO pcVO = ReportConverter.toPurchaseReportVo(pc);


                // 采购发票明细
                List<PurchaseInvoiceDetailVO> purchaseInvoices =
                    purchaseInvoiceMapper.selectByPurchaseContractId(pc.getId());
                pcVO.setPurchaseInvoiceDetails(purchaseInvoices);

                // 付款明细
                log.info("contractId{}",pc.getId());
                List<PaymentBillVO> payments = billMapper.selectPaymentsByContractId(pc.getId());
                pcVO.setPaymentBills(payments);

                purchaseVOs.add(pcVO);
            }
            vo.setPurchaseContracts(purchaseVOs);

            result.add(vo);
        }
        return result;
    }
}
